package com.servlet;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 抽象的HttpServlet
 * <p>其他的servlet请继承该抽象类</p>
 *
 * @author wang_
 * @version 2024.3.4.1
 * @description
 * @date 2025/6/25
 */
public abstract class AbstractHttpServlet extends HttpServlet {
	protected static final Logger LOG = LogManager.getLogger(AbstractHttpServlet.class);
	
	/// get请求方法
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doPost(request, response);
	}
	
	/// post请求方法
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// 处理HTML乱码
		response.setHeader("Content-Type", "text/html; charset=UTF-8");
		// 处理请求乱码
		request.setCharacterEncoding("UTF-8");
		// 处理响应乱码
		response.setCharacterEncoding("UTF-8");
		// 获取输出流
		PrintWriter out = response.getWriter();
		// 获取session
		HttpSession session = request.getSession();
		doHandle(request, response, out, session);
	}
	
	/**
	 * 处理请求
	 * <p>继承该类之后直接实现该方法</p>
	 *
	 * @param request  请求
	 * @param response 响应
	 * @param out      输出流
	 * @param session  会议
	 * @throws IOException 抛出IO异常
	 */
	public abstract void doHandle(HttpServletRequest request, HttpServletResponse response, PrintWriter out, HttpSession session) throws IOException, ServletException;
}
